//获取应用实例
const app = getApp();
import { $wuxSelect, $wuxActionSheet } from 'weapp/index'
Page({
    data: {
      is_distribution_price_edit:true,
        template_id: 0,
        detail: null,
        nav_active_index: 0,
        nav_list: [
          { id: 6, name: '计划下单' },
       
            { id: 2, name: '面料情况' },
            // { id: 3, name: '尺寸表' },
            { id: 4, name: '物料档案' },
 
            { id: 5, name: '生产计划' },
            { id: 1, name: 'BOM信息' },
  
        ],
        list_data: [],
        now_page: 0,
        list_total: 0,
        keywords: '',
        table_head: [
            { id: 1, name: '图片', field: 'images', is_checked: false, width: 70 },
            { id: 2, name: '简码', field: 'template_no', is_checked: false, width: 100 },
            { id: 20, name: '性质', field: 'type', is_checked: true, width: 80 },
            { id: 30, name: '完成率', field: 'jindu', is_checked: true, width: 120 },
            // {id: 3, name: 'bom总数', field: 'total_bom_num', is_checked: true, width: 120},
            // {id: 7, name: '未采购', field: 'less_purchase', is_checked: true, width: 120},
            // {id: 4, name: '已采购', field: 'purchase_bom_num', is_checked: true, width: 120},
            // {id: 5, name: '无需采购', field: 'no_purchase', is_checked: true, width: 120},
            { id: 8, name: '需求总量', field: 'total_need_num', is_checked: true, width: 120 },
            { id: 11, name: '未采购总量', field: 'unreceived', is_checked: true, width: 150 },
            { id: 10, name: '已采购总量', field: 'total_caigou_num', is_checked: true, width: 150 },
            { id: 9, name: '无需采购总量', field: 'no_total_need_num', is_checked: true, width: 180 },
            { id: 6, name: '已到齐', field: 'reach_num', is_checked: true, width: 120 },
        ],
        batch_bom_list:[],
        table_scroll_left: 0,
        table_scroll_left_size: 0,
        table_head_size: [
            { id: 1, name: '28\\44\\160\\37\\S', field: 'first', is_checked: true, width: 210 },
            { id: 1, name: '29\\46\\165\\38\\M', field: 'second', is_checked: true, width: 210 },
            { id: 1, name: '30\\48\\170\\39\\L', field: 'third', is_checked: true, width: 210 },
            { id: 1, name: '31\\>50\\175\\40\\XL', field: 'fourth', is_checked: true, width: 230 },
            { id: 1, name: '32\\52\\180\\41\\2XL', field: 'fifth', is_checked: true, width: 230 },
            { id: 1, name: '33\\54\\185\\42\\3XL', field: 'sixth', is_checked: true, width: 230 },
            { id: 1, name: '34\\56\\190\\43\\4XL', field: 'seventh', is_checked: true, width: 230 },
            { id: 1, name: '35\\58\\195\\44\\5XL', field: 'eighth', is_checked: true, width: 230 },
            { id: 1, name: '36\\6XL\\200', field: 'ninth', is_checked: true, width: 180 },
            { id: 1, name: '38\\7XL', field: 'tenth', is_checked: true, width: 130 },
            { id: 1, name: '40', field: 'eleven', is_checked: true, width: 100 },
            { id: 1, name: '42\\均码', field: 'twelve', is_checked: true, width: 135 },
            { id: 1, name: '误差', field: 'diff', is_checked: true, width: 120 },
        ],

        template_bom_list_config: [
            { id: 1, name: '面料名称', field: 'material_name', is_checked: true, width: 210 },
            { id: 1, name: '单件用量', field: 'single_piece', is_checked: true, width: 210 },
            { id: 1, name: '单价', field: 'price', is_checked: true, width: 210 },
            { id: 1, name: '单位', field: 'unit', is_checked: true, width: 210 },
        ],
        template_bom_list: [],

        supplier_list: [],
        supplier_total: 0,
        supplier_now_page: 0,
        supplier_keywords: '',


        show_config: {
            show: false,//显示表单
            show_share: false,//显示操作面板
        },
        material_show_config: {
            show: false,//显示表单
            show_share: false,//显示操作面板
        },
        //计划采购管理配置
        batch_show_config: {
          show: false,//显示表单
        },
        bom_form: {
            material_type: '',
            material_type_index: '',
            bom_name: '',
            price: '',
            single_piece: '',
            bom_detail_id: 0
        },
        material_type_list: [],
        bom_type_list: [
            { id: 1, name: '面料' },
            { id: 2, name: '辅料' },
            { id: 3, name: '通色辅料' }
        ],
        options: [
            { name: '编辑bom', icon: 'https://img.yzcdn.cn/vant/custom-icon-light.png' },
            { name: '删除bom', icon: 'https://img.yzcdn.cn/vant/custom-icon-fire.png' },
        ],
        options2: [
            { name: '编辑面料', icon: 'https://img.yzcdn.cn/vant/custom-icon-light.png' },
            { name: '计划采购管理', icon: 'https://img.yzcdn.cn/vant/custom-icon-light.png' },
        ],
        formData: {
            material_sku_id: '',
            material_id: '',
            purchase_date: '',
            purchase_user: 0,
            supply_id: 0,
            material_name: '',
            material_type: '',
            unit: '',
            price: '',
            cloth_width: '',
            gram_weight: '',
            no_use_rate: '',
            material_attr: '',
            material_grade: '',
            remark: '',
            remark_second: '',
            fileList2: [],
            dead_line: '',
            order_num: '',
        },
        buyer_list: [],
        buyer_list_column: [],
        show_insert_supply_form_config: {
            show: false,
        },
        supply_form: {
            SupplyNa: '',
            SupplyName: ''
        },
        /**生产计划**/
        batchList: [],
        batch_form_config: {//计划弹窗
            show: false,
        },
        batch_supply_form_config: {//计划弹窗的供应商弹窗
            is_show_choose_supplier: false,
            is_shade_screen: false,
        },
        batch_form: {
            id: 0,
            batch_name: '',
            template_cost:'',
            factory_id: 0,
            // SupplyNa: "",
            grade_category: '',
            skus: [],
        },
        batch_form2: {
          goods_purchase_id: 0,
          purchase_type: '',
          supply_id: 0,
          skus: [],
        },
        batch_form_config2: {//计划弹窗
          show: false,
        },
        /**生产计划**/

        // 外发工厂
        is_show_half: false,
        is_show_shade: false,
        factory_list: [],
        factory_list_column: [],
        factory_total: 0,
        factory_page: 0,
        factory_keywords: '',
        choose_factory: [],
        TypeOptions:[],
        TypeOptionsCol:[],
        purchase_table_head: [
          {id: 1, name: '件数', field: 'plan_total_num', is_checked: true, width: 100, show_user: [0]},
          {id: 6, name: '铺货区域', field: 'paving_area', is_checked: true, width:110, show_user: [0]},
          {id: 3, name: '采购价', field: 'purchase_price', is_checked: true, width:110, show_user: [0]},
          {id: 4, name: '零售价', field: 'sale_price', is_checked: true, width: 100, show_user: [0]},
          {id: 5, name: '分销价', field: 'distribution_price', is_checked: true, width: 100, show_user: [0]},
          {id: 2, name: '交期', field: 'expected_completion_date', is_checked: true, width: 160, show_user: [0]},
        ],
    },

    // 采购时间
    bindPurchaseDateChange: function (e) {
        this.setData({
            [`formData.purchase_date`]: e.detail.value
        })
    },

    bindBatchDateChange: function (e) {
      let index = e.currentTarget.dataset.index
      let field = e.currentTarget.dataset.field
      this.setData({
          [`batch_bom_list[${index}].${field}`]: e.detail.value
      })
  },
  batch_purchase_num_change(e){
    let {index,field} = e.currentTarget.dataset
    this.setData({
      [`batch_bom_list[${index}].${field}`]: e.detail.value
    })
  },
    // 交期
    bindDeadlineChange: function (e) {
        this.setData({
            [`formData.dead_line`]: e.detail.value
        })
    },
    is_distribution_price_edit() {
      var result = app.request_api('admin/template/is_distribution_price_edit', {
      }, false);
      result.then(res => {
        this.setData({
          is_distribution_price_edit:res.is_edit
        })
      })
    },
    // 采购员改变时
    buyerChange: function (e) {

        this.setData({
            [`formData.purchase_user`]: this.data.buyer_list[parseInt(e.detail.value)].id,
            [`sel_text.buyer_text`]: this.data.buyer_list[parseInt(e.detail.value)].realname
        })
    },

    chooseDel3: function (e) {
      var index = e.currentTarget.dataset.index;
      this.data.batch_form2.skus.splice(index, 1);
      // 重置data
      this.setData({
          [`batch_form2.skus`]: this.data.batch_form2.skus
      });
  },

    /**
     * 生产计划
     */
    // 搜索工厂
    halfBottomSearch: function (events) {
        var keywords = events.detail.value.trim();
        this.setData({
            factory_keywords: keywords,
            factory_list: [],
            factory_page: 0,
            factory_total: 0
        });
        this.get_factory_list(1);
    },
    // 选择加工厂时
    choose_factory: function (events) {
        var index = events.currentTarget.dataset.index;
        var id = this.data.factory_list[index].id
        var SupplyNa = this.data.factory_list[index].SupplyNa
        let choose_factory = []
        choose_factory.push(SupplyNa);
        console.log('id',id)
        this.setData({
            choose_factory: choose_factory,
            [`batch_form.factory_id`]: id,
            [`batch_form2.supply_id`]: id,
            is_show_shade: false,
            is_show_half: false
        })
    },

    // 删除选择项
    DeleteChoose: function (events) {
        var index = events.currentTarget.dataset.index;
 
        this.data.choose_factory.splice(index, 1);
        console.log(index, this.data.choose_factory)
        this.setData({
            choose_factory: this.data.choose_factory,
            [`batch_form.factory_id`]: 0
        });
    },

    // 关闭半屏
    close_half: function (e) {
        this.setData({
            is_show_shade: false,
            is_show_half: false
        })
    },

    // 打开半屏
    open_half: function (e) {
        this.setData({
            is_show_shade: true,
            is_show_half: true
        })
    },
    // 获取外发工厂
    get_factory_list: function (is_search = 0) {
        var __this = this;
        // 验证
        if ((this.data.factory_list.length >= this.data.factory_total) && this.data.factory_page > 0) {
            return false;
        }
        // 发起请求
        var result = app.request_api('admin/Factory/index', {
            page: __this.data.factory_page + 1,
            quick_search: __this.data.factory_keywords,
            limit: 100,
        }, false);
        result.then(res => {
            console.log(res)
            if (is_search == 1) {
                __this.setData({
                    factory_list: [],
                    factory_page: 0,
                    factory_total: 0
                })
            }
            let factory_list_column = {};
            res.list.forEach((v, k) => {
                factory_list_column[v.id] = v;
            })
            console.log('factory_list_column', factory_list_column)
            __this.setData({
                factory_list: __this.data.factory_list.concat(res.list),
                factory_list_column,
                factory_page: this.data.factory_page + 1,
                factory_total: res.total
            })
        });
    },
    // 选择颜色
    // 当输入生产数量时
    selInputChange: function (e) {
        var index = e.currentTarget.dataset.index;
        var field = e.currentTarget.dataset.field;
        this.data.batch_form.skus[index][field] = e.detail.value;
        this.setData({
            [`batch_form.skus`]: this.data.batch_form.skus
        })
    },
    selInputChange2: function (e) {
      var index = e.currentTarget.dataset.index;
      var field = e.currentTarget.dataset.field;
      this.data.batch_form2.skus[index][field] = e.detail.value;
      this.setData({
          [`batch_form2.skus`]: this.data.batch_form2.skus
      })
  },
    batch_info_input: function (e) {
        let { field, index } = e.currentTarget.dataset
        let { value } = e.detail;
        this.setData({
            [`batch_form.${field}`]: value,
        })
    },
    // 取消选择
    chooseDel: function (e) {
        var index = e.currentTarget.dataset.index;
        this.data.batch_form.skus.splice(index, 1);
        // 重置data
        this.setData({
            [`batch_form.skus`]: this.data.batch_form.skus
        });
    },

    ChooseColor: function (events) {
        var __this = this;
        // 打开选择颜色页面
        wx.navigateTo({
            url: '/pages/choose_color/choose_color?template_id='+__this.data.template_id,
            events: {
                // 当选择完成时
                changeData: function (data) {
                    console.log('选择完成',data);
      
                    __this.setData({
                        [`batch_form.skus`]: data,
                    });

                    const filteredData = data.filter(item => !item.hasOwnProperty('batch_color_id'));

                    var names = filteredData.map((v)=>v.name);
                     __this.getTemplateColorPrices(__this.data.template_id,names);
                }
            },
            success: function (res) {
                // 向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    sel_list: __this.data.batch_form.skus,
                    template_id: __this.data.template_id
                });
            }
        });
    },
    ChooseColor2: function (events) {
      var __this = this;
      // 打开选择颜色页面
      wx.navigateTo({
          url: '/pages/choose_color/choose_color?template_id='+__this.data.template_id,
          events: {
              // 当选择完成时
              changeData: function (data) {
                  console.log('选择完成',data);
    
                  __this.setData({
                      [`batch_form2.skus`]: data
                  });

                  const filteredData = data.filter(item => !item.hasOwnProperty('batch_color_id'));

                  var names = filteredData.map((v)=>v.name);
                   __this.getTemplateColorPrices(__this.data.template_id,names);
              }
          },
          success: function (res) {
              // 向被打开页面传送数据
              res.eventChannel.emit('acceptDataFromOpenerPage', {
                  sel_list: __this.data.batch_form2.skus,
                  purchase_table_head: __this.data.purchase_table_head,
                  template_id: __this.data.template_id
              });
          }
      });
  },

    getTemplateColorPrices(template_id,colors){
      var result = app.request_api('admin/template/getTemplateColorInfo', {
        template_id,
        colors:colors
      }, false,'post');
      result.then(res => {
        console.log(' batch_form.skus', this.data.batch_form.skus,res)
        this.data.batch_form.skus.forEach((v,k)=>{
            if(res[v.name]!==undefined){
              v.goods_id=res[v.name].goods_id
              v.distribution_price=res[v.name].distribution_price
              v.sale_price=res[v.name].sale_price
            }
        })

        this.setData({
          batch_form:this.data.batch_form
        })
      });
    },
    
    showForm2(e) {
      let index = e.currentTarget.dataset.index
      let id = e.currentTarget.dataset.id
      let choose_factory = []
      let batch_form2 = {}
      console.log('goods_purchase_id',id);
      if (id !== undefined || index !== undefined) {
          let data = this.data.batchList2[index];
          for (var k in this.data.batch_form2) {
              batch_form2[k] = data[k];
          }
          
          let skus = []
          data.skus.forEach((v) => {
              skus.push({...v, name: v.name, plan_total_num: v.plan_total_num })
          })
          console.log('skusskusskusskusskusskus',skus)
          batch_form2.skus = skus
          if (data.SupplyNa != '' && data.SupplyNa !== undefined && data.SupplyNa !== null) {
              choose_factory.push(data.SupplyNa)
          }

      } else {
          batch_form2.goods_purchase_id = 0
          batch_form2.purchase_type = ''
          batch_form2.supply_id = 0
          batch_form2.skus = []
      }
      console.log('batch_form2batch_form2batch_form2batch_form2batch_form2',batch_form2)
      this.setData({
          choose_factory,
          [`batch_form2`]: batch_form2
      });
      this.get_factory_list();
      this.get_type_options();
      this.setData({
          [`batch_form_config.show`]: true,
      });
  },
    showForm(e) {
        let index = e.currentTarget.dataset.index
        let id = e.currentTarget.dataset.id
        let choose_factory = []
        let batch_form = {}
        let batch_form2 = {}
        if (id !== undefined || index !== undefined) {
            let data = this.data.batchList[index];
            for (var k in this.data.batch_form) {
                batch_form[k] = data[k];
            }
            
            let skus = []
            data.skus.forEach((v) => {
                skus.push({...v, name: v.color, num: v.quantity })
            })
            batch_form.skus = skus
            if (data.SupplyNa != '' && data.SupplyNa !== undefined && data.SupplyNa !== null) {
                choose_factory.push(data.SupplyNa)
            }

        } else {
            batch_form.id = 0
            batch_form.batch_name = ''
            batch_form.factory_id = 0
            batch_form.grade_category = ''
            batch_form.template_cost = ''
            batch_form.skus = []


            batch_form2.goods_purchase_id = 0
            batch_form2.purchase_type = ''
            batch_form2.supply_id = 0
            batch_form2.skus = []
        }
        this.setData({
            choose_factory,
            [`batch_form`]: batch_form,
            [`batch_form2`]: batch_form2
            
        });
        this.get_factory_list();
        this.get_type_options();
        this.setData({
            [`batch_form_config.show`]: true,
        });
    },
    hideForm() {
        this.setData({
            [`batch_form_config.show`]: false,
        });
    },

    TypeOptionsChange(e){
        let index = e.detail.value
        let value = this.data.TypeOptions[index].label
        this.setData({
            [`batch_form.batch_name`]:value
        })
    },
    /*new*/
    TypeOptionsChange2(e){
      let index = e.detail.value
      let value = this.data.TypeOptions[index].value
      this.setData({
          [`batch_form2.purchase_type`]:value
      })
    },
    /*new*/
    get_type_options(){
        var result = app.request_api('admin/ProductBatch/getTypeOptions', {
        }, false);
        result.then(res => {
            let data = res.list
            let data2 = []
            data.forEach((item)=>{
              data2[item.value] = item.label
            })

            this.setData({
                TypeOptions:data,
                TypeOptionsCol:data2,
            })
        });
    },
    getBatchList() {
        var result = app.request_api('admin/ProductBatch/getBatchIndex', {
            template_id: this.data.template_id
        }, false);
        result.then(res => {
            this.setData({
                batchList: res,
            });
        });
    },
    getBatchList2() {
      var result = app.request_api('admin/ProductBatchOrder/getPurchseOrderIndex', {
          template_id: this.data.template_id
      }, false);
      result.then(res => {
          this.setData({
              batchList2: res.list,
          });
      });
    },
    
    saveBatch2() {
      let formData = {}
      formData.template_id = this.data.template_id;
      formData.is_xcx = true;
      let skus = [];
      let old_skus = this.data.batch_form2.skus
      this.data.batch_form2.skus.forEach((v, k) => {
          skus.push(v)
      })
      this.data.batch_form2.skus = skus
      formData.formData = this.data.batch_form2
      console.log('formDataformDataformDataformDataformData',formData)
      // return;
      if (this.data.batch_form2.goods_purchase_id !== undefined && this.data.batch_form2.goods_purchase_id != 0  ) {
          var result = app.request_api('admin/ProductBatchOrder/updatePurchaseOrder', formData, true, 'POST', {}, true);
      } else {
          var result = app.request_api('admin/ProductBatchOrder/createPurchaseOrder', formData, true, 'POST', {}, true);
      }
      //
      result.then(res => {
          this.hideForm();
          this.getBatchList();
          this.getBatchList2();
          return;
      }).catch(() => {
        this.data.batch_form2.skus = old_skus
      })
  },
    /**生产计划 */
    /**bom */

    show_insert_supply_form() {
        this.setData({
            [`show_insert_supply_form_config.show`]: true
        })
    },
    saveBatch() {
        this.data.batch_form.template_id = this.data.template_id;
        let skus = [];
        let old_skus = this.data.batch_form.skus
        this.data.batch_form.skus.forEach((v, k) => {
            skus.push({ 
              color: v.name,
               quantity: v.num,
                delivery_time: v.delivery_time,
                purchase_price:v.purchase_price,
                sale_price:v.sale_price,
                distribution_price:v.distribution_price,
               })
        })
        this.data.batch_form.skus = skus
        if (this.data.batch_form.id != 0 && this.data.batch_form.id !== undefined) {
            var result = app.request_api('admin/ProductBatch/editBatch', this.data.batch_form, true, 'POST', {}, true);
        } else {
            var result = app.request_api('admin/ProductBatch/addBatch', this.data.batch_form, true, 'POST', {}, true);
        }
        //
        result.then(res => {
            this.hideForm();
            this.getBatchList();
            return;
        }).catch(() => {
          this.data.batch_form.skus = old_skus
        })
    },
    delBatch(e) {
        let index = e.currentTarget.dataset.index
        let batchList = this.data.batchList
        let _this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要删除计划吗',
            success(res) {
                if (res.confirm) {
                    var result = app.request_api('admin/ProductBatch/removeBatch', { id: batchList[index].id }, true, 'POST', {}, true);
                    result.then(res => {
                        batchList.splice(index, 1)
                        _this.setData({
                            batchList
                        })
                        wx.showModal({
                            title: '提示',
                            content: res.msg,
                            showCancel: false,
                            complete() {

                            }
                        });
                        this.getBatchList();
                    })
                }
            },
        });

    },
    // 添加选项
    // add_factory: function (events) {
    //     var keywords = this.data.factory_keywords.trim();
    //     if (keywords == '') {
    //         wx.showToast({
    //             title: '请输入后再添加',
    //             icon: 'none',
    //             duration: 1500,
    //         });
    //         return false;
    //     }
    //     let choose_factory = []
    //     choose_factory.push(keywords);
    //     this.setData({
    //         choose_factory: choose_factory,
    //         factory_keywords: '',
    //         factory_list: [],
    //         factory_page: 0,
    //         factory_total: 0,
    //         [`batch_form.factory_id`]: 0,
    //         // [`batch_form.SupplyNa`]: keywords,
    //         is_show_shade: false,
    //         is_show_half: false
    //     });
    //     // this.get_factory_list();
    // },
    // 打开选择
    open_supplier_choose: function () {
        this.setData({
            is_shade_screen: true,
            is_show_choose_supplier: true
        })
    },
    // 选择供应商
    choose_supplier: function (e) {
        // 验证是否选择的是否和之前一样
        this.setData({
            [`formData.supply_id`]: this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].id,
            [`sel_text.supply_text`]: this.data.supplier_list[parseInt(e.currentTarget.dataset.index)].SupplyNa
        });
        this.close_supplier_choose();
    },
    // 关闭
    close_supplier_choose: function (e) {
        this.setData({
            is_shade_screen: false,
            is_show_choose_supplier: false,
            is_show_choose_pro: false,
        })
    },
    // 获取采购员
    get_buyer_list: function () {
        // 发起请求
        var result = app.request_api('admin/auth.admin/index', {
            select: true,
            limit: 9999,
            group_id: 7
        }, false);
        result.then(res => {
            let buyer_list_column = {};
            res.list.forEach((v, k) => {
                buyer_list_column[v.id] = v;
            })
            this.setData({
                buyer_list_column,
                buyer_list: res.list
            });
        });
        // 返回
        return result;
    },
    material_info_input: function (e) {
        let { field, index } = e.currentTarget.dataset
        let { value } = e.detail;
        this.setData({
            [`formData.${field}`]: value,
        })
    },
    newsupply_info_input: function (e) {
        let { field, index } = e.currentTarget.dataset
        let { value } = e.detail;
        this.setData({
            [`supply_form.${field}`]: value,
        })
    },
    closeSupply() {
        this.setData({
            [`show_insert_supply_form_config.show`]: false,
        })
    },
    insertSupply() {
        if (this.data.supply_form.SupplyNa == '' || this.data.supply_form.SupplyName == '') {
            wx.showModal({
                title: '提示',
                content: '请填写完整',
                showCancel: false,
                complete() {

                }
            });
            return;
        }
        var result = app.request_api('admin/supply/add', { SupplyNa: this.data.supply_form.SupplyNa, SupplyName: this.data.supply_form.SupplyName }, true, 'post', {}, true);
        result.then(res => {
            wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                complete() {

                }
            });
            this.setData({
                ['supplier_now_page']: 0,
                [`show_insert_supply_form_config.show`]: false,
            })
            this.get_supplier_list(1);
        })
    },
    // 搜索供应商时
    searchSupplierChange: function (events) {
        var keywords = events.detail.value.trim();

        this.setData({
            [`formData.supply_id`]: keywords,
            [`sel_text.supply_text`]: keywords,
            supplier_keywords: keywords,
            supplier_list: [],
            supplier_now_page: 0,
            supplier_total: 0,
        });
        this.get_supplier_list(1);
    },
    onShareSelect2(e) {
        let index = e.detail.index;
        if (index == 0) {
            if (this.data.formData.material_sku_id == 0) {
                wx.showModal({
                    title: '提示',
                    content: '没找到面料',
                    showCancel: false,
                    complete() {

                    }
                });
                return;
            }
            this.get_buyer_list()
            this.get_supplier_list()
            this.get_MaterialCategory_list();
            var result = app.request_api('admin/material/sku_get', { material_sku_id: this.data.formData.material_sku_id }, true, 'get', {}, true);
            result.then(res => {
                this.onShareClose2()
                console.log('res', res)
                let form_data = [];
                let formData = this.data.formData
                for (var k in this.data.formData) {
                    if (res.data[k] !== undefined) {
                        formData[k] = res.data[k]
                    } else {
                        formData[k] = ''
                    }
                }


                this.setData({
                    formData,
                    [`sel_text.supply_text`]: res.data.SupplyNa
                })
                this.onClickShow2()
            })
        }

        if (index == 1) {
          this.setData({
            ['material_show_config.show_share']:false,
            ['batch_show_config.show']:true
          })
          var result = app.request_api('admin/TemplateBomColor/getBomBatchList', { template_bom_color_id: this.data.formData.template_bom_color_id }, true, 'post', {}, true);
          result.then(res => {
             this.setData({
               batch_bom_list:res.data
             })
          })
        }

    },
    batch_bom_edit(e){
      let index = e.currentTarget.dataset.index
      this.setData({
        [`batch_bom_list[${index}].editing`] :!this.data.batch_bom_list[index].editing,
      })
    },
    batch_bom_save(e){
      let index = e.currentTarget.dataset.index
      var result = app.request_api('admin/TemplateBomColor/setBomBatchInfo', this.data.batch_bom_list[index], false,'POST',{},true);
      result.then(res => {
        console.log(res)
          if(res.code==1){
            wx.showToast({
              title: res.msg,
              icon: 'success',
              duration: 2000
            });
          }
      })
      console.log('batch_bom_list[index]',)
    },
    close_batch_form(){
      this.setData({
        ['batch_show_config.show']:false
      })
    },
    onClickShareShow2: function (e) {
        let { index } = e.currentTarget.dataset
        console.log(this.data.template_bom_list[index])
        let material_sku_id = this.data.template_bom_list[index].material_sku_id
        let template_bom_color_id = this.data.template_bom_list[index].id
        this.setData({
            ['formData.material_sku_id']: material_sku_id,
            ['formData.template_bom_color_id']: template_bom_color_id,
            ['material_show_config.show_share']: true
        })
    },
    onClickShow2: function (e) {
        this.setData({
            ['material_show_config.show']: true
        })
    },
    onClickHide2: function (e) {
        this.setData({
            ['material_show_config.show']: false
        })
    },
    // 获取供应商
    get_supplier_list: function (is_search = 0) {
        var __this = this;
        // 验证
        if ((this.data.supplier_list.length >= this.data.supplier_total) && this.data.supplier_now_page > 0) {
            console.log('终止', (this.data.supplier_list.length >= this.data.supplier_total), this.data.supplier_now_page)
            return false;
        }
        // 发起请求
        var result = app.request_api('admin/Supply/index', {
            page: __this.data.supplier_now_page + 1,
            quick_search: __this.data.supplier_keywords,
            limit: __this.data.limit,
            select:true,
        }, false);
        result.then(res => {
            if (is_search == 1) {
                __this.setData({
                    supplier_list: [],
                    supplier_now_page: 0,
                    supplier_total: 0
                })
            }
            __this.setData({
                supplier_list: __this.data.supplier_list.concat(res.list),
                supplier_now_page: this.data.supplier_now_page + 1,
                supplier_total: res.total
            })
        });
        // 返回
        return result;
    },
    onShareClose2: function (e) {
        this.setData({
            ['material_show_config.show_share']: false
        })
    },
    template_purchase: (e) => {
        let { template_id } = e.currentTarget.dataset;
        wx.navigateTo({
            url: '/pages/material/index?template_id=' + template_id,
        })
    },
    onClickShow: function (e) {
        this.setData({
            ['show_config.show']: true
        })
    },
    // 获取面料类型
    get_MaterialCategory_list: function () {
        // 发起请求
        var result = app.request_api('admin/MaterialCategory/index', {
            select: true,
            limit: 9999,
            group_id: 7
        }, false);
        result.then(res => {
            var newlist = [];
            res.list.forEach(function (v, k) {
                newlist[v.id] = v;
            })
            this.setData({
                material_type_list: res.list,
                material_type_list_new: newlist
            });
        });
        // 返回
        return result;
    },
    onClickShareShow: function (e) {
        let { index } = e.currentTarget.dataset
        console.log('aa')
        let index2 = this.data.bom_type_list.findIndex(res => res.name == this.data.detail.bom_list[index].material_type)
        this.data.detail.bom_list[index].material_type_index = index2
        this.setData({
            'bom_form': this.data.detail.bom_list[index],
        })
        this.setData({
            ['show_config.show_share']: true
        })
    },
    onClickHide: function (e) {
        this.setData({
            ['show_config.show']: false
        })
    },
    onShareClose: function (e) {
        this.setData({
            ['show_config.show_share']: false
        })
    },
    bom_input_change: function (e) {
        let { field } = e.currentTarget.dataset
        let { value } = e.detail
        if (field == 'price' || field == 'single_piece') {
            const regex = /^[0-9]*(\.[0-9]*)?$/;
            value = value.replace(/[^0-9.]/g, '');
        }
        this.setData({
            [`bom_form.${field}`]: value
        })
        console.log(this.data.bom_form)
    },
    // 获取上传标识
    get_web_config: function () {
        // 发起请求
        var result = app.request_api('admin/index/index', {}, true, 'GET');
        result.then(res => {
            this.setData({
                web_data: res
            });
        });
    },
    saveMaterial: function (e) {
        var __this = this
        var req_arr = []
        let formData = this.data.formData
        var substring = 'babiboy';
        if (formData.fileList2 !== undefined) {
            var fileList2 = formData.fileList2
            fileList2.forEach(function (v, k) {
                if (v.tempFilePath !== undefined && !v.tempFilePath.includes(substring)) {
                    var result = app.request_upload('', {
                        cdn_url: __this.data.web_data.siteConfig.apiUrl,
                        token: __this.data.web_data.siteConfig.upload.token,
                        is_old_file: 0
                    }, v.tempFilePath, k, false);
                    req_arr.push(result);
                    // 处理结果
                    result.then(res => {
                        let insert_data = {
                            "url": res.file_path,
                            "thumb": res.file_path,
                            "fileType": "image",
                            "value": res.file_key
                        }
                        console.log('insert_data', insert_data)
                        formData.fileList2[res.for_i] = insert_data;
                        __this.setData({
                            formData,
                        });
                    });
                }
                if (v.thumb !== undefined && !v.thumb.includes(substring)) {
                    var result = app.request_upload('', {
                        cdn_url: __this.data.web_data.siteConfig.apiUrl,
                        token: __this.data.web_data.siteConfig.upload.token,
                        is_old_file: 0
                    }, v.thumb, k, false);
                    req_arr.push(result);
                    // 处理结果
                    result.then(res => {
                        let insert_data = {
                            "url": res.file_path,
                            "thumb": res.file_path,
                            "fileType": "image",
                            "value": res.file_key
                        }
                        formData.fileList2[res.for_i] = insert_data;
                        __this.setData({
                            formData,
                        });
                    });
                }
            })
        }
        console.log('提交', this.data.formData)
        Promise.all(req_arr).then(res => {
            var result = app.request_api('admin/Material/mini_save_material', this.data.formData, true, 'POST', {}, true);
            result.then(res => {
                wx.showToast({
                    title: res.msg,
                    icon: 'success',
                    duration: 2000
                });
                this.onClickHide2()
            })
        })

    },
    saveBom: function (e) {
        let data = {
            material_type: this.data.bom_form.material_type,
            template_id: this.data.template_id,
            bom_detail_id: this.data.bom_form.bom_detail_id,
            bom_name: this.data.bom_form.bom_name,
            price: this.data.bom_form.price,
            single_piece: this.data.bom_form.single_piece,
        };
        var result = app.request_api('admin/Template/mini_save_bom', data, true, 'POST', {}, true);
        result.then(res => {
            wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 2000,
            });
            this.onClickHide();
            this.get_template_detail()
        })
    },
    materialTypeChange2(e) {
        let index = e.detail.value
        this.setData({
            [`formData.material_type`]: this.data.material_type_list[index].id,
            [`formData.material_type_index`]: index
        })
    },
    deleteImage(e) {
        // wx.showToast({
        //     title:'点击了删除',
        //     icon: 'success',
        //     duration: 2000,
        // });
        let index2 = e.detail.index
        let formData = this.data.formData
        formData.fileList2.splice(index2, 1);
        this.setData({
            formData
        })
    },
    afterRead2(event) {
        var __this = this;
        const { file } = event.detail;
        const fileList = this.data.formData.fileList2 || [];
        fileList.push({ ...file });
        var setname = `formData.fileList2`;
        this.setData({ [setname]: fileList });
    },
    materialTypeChange(e) {
        let index = e.detail.value
        this.setData({
            [`bom_form.material_type`]: this.data.bom_type_list[index].name,
            [`bom_form.material_type_index`]: index
        })
    },
    onShareSelect(e) {
        let index = e.detail.index;
        if (index == 0) {
            this.onClickShow()
        } else if (index == 1) {
            this.mini_del_bom()
        }
        this.onShareClose()
    },
    mini_del_bom() {
        let data = {
            template_id: this.data.template_id,
            bom_detail_id: this.data.bom_form.bom_detail_id,
        };
        var result = app.request_api('admin/Template/mini_del_bom', data, true, 'POST', {}, true);
        result.then(res => {
            // wx.showToast({
            //     title: res.msg,
            //     icon: 'success',
            //     duration: 2000,
            // });
            this.onClickHide();
            this.get_template_detail()
        })
    },

    getTemplateBom() {
        var template_id = this.data.template_id
        var result = app.request_api('admin/TemplateBomColor/getTemplateColor', {
            template_id,
        }, false);
        result.then(res => {
            let new_list = {};
            res.forEach((v, k) => {
                new_list[v.id] = v;
            })
            this.setData({
                template_bom_list: res,
                template_bom_list_column: new_list
            })
        })
    },
    /**bom */
    onLoad: function (options) {
        // 设置标题
        wx.setNavigationBarTitle({
            title: '样板详情'
        });
        // 设置模板
        if (options.template_id != undefined) {
            this.setData({
                template_id: options.template_id
            });
            // 获取模板详情
            this.get_template_detail();
            this.getTemplateBom();
            this.getBatchList();
            this.getBatchList2();
            this.is_distribution_price_edit();
        }
        this.get_web_config();
    },

    // 表格滑动结束
    tr_boxs_scroll_end: function (e) {
        var __this = this;
        setTimeout(function () {
            __this.setData({
                table_scroll_left: e.detail.scrollLeft
            });
        }, 180);
    },

    // 尺寸表格滑动结束
    tr_boxs_scroll_end2: function (e) {
        var __this = this;
        setTimeout(function () {
            __this.setData({
                table_scroll_left_size: e.detail.scrollLeft
            });
        }, 180);
    },

    // 获取样板详情
    get_template_detail: function () {
        var result = app.request_api('admin/Template/edit', {
            template_id: this.data.template_id
        }, true, 'GET');
        result.then(res => {
            console.log(res);
            this.setData({
                detail: res.row
            });
            // 获取面料情况
            if (res.row.template_no != '') {
                this.get_list_data();
            }
        });
    },

    // 获取列表数据
    get_list_data: function (is_search = 0) {
        // 验证
        if ((this.data.list_data.length >= this.data.list_total) && this.data.now_page > 0) {
            return false;
        }
        // 组装参数
        var req_data = {
            page: this.data.now_page + 1,
            limit: 9999,
            quick_search: this.data.detail.template_no
        };
        // 发起请求
        var result = app.request_api('admin/TotalBom/index?order=total_bom_id,desc', req_data, false);
        result.then(res => {
            console.log(res)
            if (is_search == 1) {
                this.setData({
                    list_data: [],
                    now_page: 0,
                    list_total: 0,
                })
            }
            this.setData({
                list_data: this.data.list_data.concat(res.list),
                list_total: res.total,
                now_page: this.data.now_page + 1,
            });
        })
    },

    // 预览图片
    PreviewImg: function (events) {
        var pic_arr = events.currentTarget.dataset.pic;
        if (pic_arr.length == 0) {
            return false;
        }
        // 调用
        wx.previewImage({
            current: pic_arr[0],
            urls: pic_arr
        })
    },

    // 展示更多
    showMore: function (events) {

        var index = events.currentTarget.dataset.index;

        var content = this.data.detail.bom_list[index].bom_name;
        wx.showToast({
            title: content,
            icon: 'none',
            duration: 3000,
        });
    },

    // 编辑样板
    template_update: function (events) {
        var __this = this;
        // 跳转
        wx.navigateTo({
            url: '/pages/template_add/template_add?template_id=' + __this.data.detail.template_id,
            events: {
                // 当修改完成时
                changeData: function (data) {
                    // 重新请求数据
                    __this.get_template_detail();
                }
            }
        });
    },

    // 关闭生产
    template_close: function (events) {
        var __this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要关闭生产吗',
            success(res) {
                if (res.confirm) {
                    __this.template_close_request();
                }
            },
        });
    },

    // 关闭生产请求
    template_close_request: function (index) {
        var __this = this;
        var template_id = __this.data.detail.template_id;
        var result = app.request_api('admin/template/closeTemplate', {
            id: template_id
        }, true);
        result.then(res => {
            wx.showToast({
                title: '已关闭生产',
                icon: 'none',
                duration: 2000,
            });
            __this.data.detail.status = 99;
            __this.setData({
                detail: __this.data.detail
            });
            // 向上一级页面传递参数
            var eventChannel = __this.getOpenerEventChannel();
            eventChannel.emit('changeCloseData', {});
        });
    },

    // 确认生产
    template_product: function (events) {
        var __this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要开始生产吗',
            success(res) {
                if (res.confirm) {
                    __this.template_product_request();
                }
            },
        });
    },

    // 确认生产请求
    template_product_request: function (index) {
        var __this = this;
        var template_id = __this.data.detail.template_id;
        var result = app.request_api('admin/template/postConfirmProduct', {
            template_id: template_id
        }, true);
        result.then(res => {
            wx.showToast({
                title: '已开始生产',
                icon: 'none',
                duration: 2000,
            });
            // 修改状态
            __this.data.detail.status = 3;
            __this.setData({
                detail: __this.data.detail
            });
            // 向上一级页面传递参数
            var eventChannel = __this.getOpenerEventChannel();
            eventChannel.emit('changeProductData', {});
        });
    },

    // 切换选项卡
    ChangeNav: function (events) {
        var index = events.currentTarget.dataset.index;
        this.setData({
            nav_active_index: index
        });
    },

    // 预览图片
    PreviewImage: function (events) {
        var src = events.currentTarget.dataset.src;
        // 调用
        wx.previewImage({
            current: src,
            urls: [src]
        })
    },

    // 跳转到详情页
    GoDetail: function (events) {
        var __this = this;
        var total_bom_id = events.currentTarget.dataset.id;
        var template_no = events.currentTarget.dataset.no;
        // 打开详情页面
        wx.navigateTo({
            url: '/pages/wuliao_follow_detail/wuliao_follow_detail?total_bom_id=' + total_bom_id + '&template_no=' + template_no,
        });
    },

    // 采购时间
    bindDateChange: function (e) {
        let index = e.currentTarget.dataset.index
        var bianl = `batch_form.skus[${index}].delivery_time`;
        this.setData({
            [bianl]: e.detail.value
        })
    },
       // 采购时间
       bindDateChange2: function (e) {
        let index = e.currentTarget.dataset.index
        var bianl = `batch_form2.skus[${index}].expected_completion_date`;
        this.setData({
            [bianl]: e.detail.value
        })
    },

    // 新增供应商
    add_supply: function (e) {
        const __this = this;
        // 跳转到添加供应商界面
        wx.navigateTo({
            url: '/pages/supply_add/supply_add',
            events: {
                // 当添加完成时
                changeData: function (data) {
                    // 重新加载数据
                    __this.setData({
                        factory_keywords: data.simple_name,
                        factory_list: [],
                        factory_page: 0,
                        factory_total: 0
                    });
                    __this.get_factory_list(1);
                }
            }
        });
    },


})
